package com.lzs.lzscodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.lzs.lzscodesandbox.model.ExecuteCodeRequest;
import com.lzs.lzscodesandbox.model.ExecuteCodeResponse;
import com.lzs.lzscodesandbox.model.ExecuteMessage;
import com.lzs.lzscodesandbox.model.JudgeInfo;
import com.lzs.lzscodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class JavaNativeCodeSandboxOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    // 在黑名单中的命令是禁止的
    private static final List<String> blackList = Arrays.asList("Files","exec");

    private static final WordTree WORD_TREE;

    static{
        // 初始化字典树
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }

    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandbox = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
//        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/Main.java", StandardCharsets.UTF_8);// 读取文件的代码
//        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/unsafeCode/SleepError.java", StandardCharsets.UTF_8);// 读取文件的代码
        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/unsafeCode/ReadFileError.java", StandardCharsets.UTF_8);// 读取文件的代码
//        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/unsafeCode/MemoryError.java", StandardCharsets.UTF_8);// 读取文件的代码
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);// 调用方法传入响应，输出返回结果
        System.out.println(executeCodeResponse);

    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 校验代码是否有黑名单中的命令
        FoundWord foundWord = WORD_TREE.matchWord(code);// 检查用户代码，是否包含已经添加进来的任何一个代码
        if (foundWord != null) {
            System.out.println("包含敏感词：" + foundWord.getFoundWord());
            return null;
        }

        String userDir = System.getProperty("user.dir");// 获取到项目的根目录
        String globalCodePAthName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;// File.separator 用于匹配不同系统的 左（右）划线--> / \
        // 判断全局代码目录是否存在
        if (!FileUtil.exist(globalCodePAthName)) {
            FileUtil.mkdir(globalCodePAthName);// 不存在就新建
        }
        // 把用户代码隔离存放
        String userCodeParentPath = globalCodePAthName + File.separator + UUID.randomUUID();// 存放代码的文件夹目录
        // 实际代码文件Main.java
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        // 将用户代码写入文件
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        // 2.编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());// 代码所在文件（Main.java）的路径
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);// 执行编译代码
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);

        } catch (Exception e) {
            return getErrorResponse(e);
//            throw new RuntimeException(e);
        }
        // 3.执行代码，得到输出结果
        List<ExecuteMessage> executeMessagesList = new ArrayList<>();// 获取所有的输出结果信息列表
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);

            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);// Runtime.getRuntime()开启了新的子进程
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);// private static final long TIME_OUT = 5000L;
                        runProcess.destroy();// 睡醒还没执行完，杀死子进程
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess, inputArgs);
                System.out.println(executeMessage);
                executeMessagesList.add(executeMessage);// 将输出信息加入list
            } catch (Exception e) {
//                throw new RuntimeException(e);
                return getErrorResponse(e);
            }
        }
        // 4.收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();// 获取结果集
        // 取最大值来判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessagesList) {
            String errorMessage = executeMessage.getErrorMessage();
            // 如果有错误信息
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);// 枚举值3-执行中存在错误
                break;
            }
            // 没有错误信息将输出集加入集合
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null){
                maxTime = Math.max(maxTime,time);// 原始值与新值比较哪个大
            }
        }
        if (outputList.size() == executeMessagesList.size()){// 每一条信息都正常输出
            executeCodeResponse.setStatus(1);// 执行成功
        }
        // 将结果集放入响应对象
        executeCodeResponse.setOutputList(outputList);

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory(); 要借助第三方库获取执行内存
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5.文件清理
        if (userCodeFile.getParentFile() != null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除：" + (del ? "成功" : "失败"));
        }

        // 6.错误处理，提升程序健壮性





        return null;

    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    // 创建方法，判断错误处理（错误处理前有内部异常处理）
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
